package com.niit.wallswapers;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import java.io.IOException;

public class WallpaperChangeService extends Service implements Runnable{
    private int[] wallpaperId = {R.drawable.wallpaper1,R.drawable.wallpaper2};
    private int time;
    private int FLAG = 0;
    private Thread t;
    private Bitmap bitmap;
    private Bitmap bitmap1;
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    public int onStartCommand(Intent intent, int flag, int startId) {
        super.onStartCommand(intent,flag,startId);
        Bundle bundle = intent.getExtras();
        time = bundle.getInt("time");
        bitmap = BitmapFactory.decodeResource(getResources(), wallpaperId[0]);
        bitmap1 = BitmapFactory.decodeResource(getResources(), wallpaperId[1]);
        t = new Thread(this);
        t.start();
        return Service.START_STICKY_COMPATIBILITY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (t != null) {
            t.interrupt(); // 中断线程
        }
    }
    @Override
    public void run() {
        WallpaperChangeService context = WallpaperChangeService.this;
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
        try{
            while(true) {
                if(FLAG % 2 == 0) {
                    try {
                        wallpaperManager.setBitmap(bitmap);
                        FLAG ++ ;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    try {
                        wallpaperManager.setBitmap(bitmap1);
                        FLAG ++ ;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // Sleep for the amount of time in milliseconds
                Thread.sleep(time * 1000);
                // Flip the FLAG to switch between bitmaps
                FLAG = 1 - FLAG;
            }
        }catch (InterruptedException e) {
            // Restore the interrupted status
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}
